﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Equipment_management
{
    public partial class TableControl : UserControl
    {
        public string path; 
        public string fileName;
        public DataTable _DataTable;
        public string[] titel_str
        {
            set;
            get;
        } = new string[] { "工位名称", "IP地址" ,"端口"};

        public int[] title_width
        {
            set;
            get;
        } = new int[] { 50, 40, 20};

        public TableControl()
        {

            InitializeComponent();
            SetStyle(ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
            UpdateStyles();

            init_RightClick2();
            DataGridView_init(dataGridView1, titel_str, title_width);
            dataGridView1.ContextMenuStrip = menuStrip_1;

            //读取设备数据
            _DataTable = Deserialize<DataTable>(path +"\\" +fileName + ".config");
            if (_DataTable != null)
            {
                dataGridView1.Rows.Clear();
                GridviewShowDataTable(_DataTable, dataGridView1);
            }
        }
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        /*****************************************************************************************************************************/
        public int Save_Data()
        {
            try
            {
                _DataTable = GetDataGridView(dataGridView1);

                if (Serialize(_DataTable, path + "\\" + fileName + ".config") == 0)
                {
                    MessageBox.Show("数据保存成功！", "提示");
                }
                else
                {
                    MessageBox.Show("数据保存失败！", "提示");
                }
                return 0;
            }
            catch (Exception er)
            {
                return 1;
            }
        }

        public void DataGridView_init(DataGridView dataGridView, string[] title_str, int[] title_width, bool Edit_state = false)
        {

            //优化dataGridView控件闪耀现象
            Type dgvType = dataGridView.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(dataGridView, true, null);

            //dataGridView部分设置
            //禁止编辑后自动生成一行
            dataGridView.AllowUserToAddRows = false;
            //设置为系统表格样式
            dataGridView.EnableHeadersVisualStyles = false;
            //自适应列宽
            //dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader;
            //dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            //列头文本居中
            dataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列头文本居中

            //禁止显示列标题
            dataGridView.RowHeadersVisible = false;
            //行头边框样式                                                                                            
            dataGridView.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            //单元格文本居中
            dataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //自适应行高度
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders;
            //禁止用户改变列宽行高
            dataGridView.AllowUserToOrderColumns = false;
            dataGridView.AllowUserToResizeRows = false;
            dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dataGridView.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;

            dataGridView.AllowUserToDeleteRows = false;
            dataGridView.AllowUserToResizeColumns = false;
            dataGridView.AllowUserToResizeRows = false;

            //字体大小编辑
            dataGridView.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 10.5f, Font.Style | FontStyle.Regular);
            dataGridView.DefaultCellStyle.Font = new Font("宋体", 10.5f, Font.Style | FontStyle.Regular);


            //行头宽度
            //dataGridView.RowHeadersWidth = 15;

            //禁止编辑
            dataGridView.ReadOnly = Edit_state;

            //鼠标选定颜色
            dataGridView1.DefaultCellStyle.SelectionBackColor = SystemColors.Highlight;
            dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;

            //增加列头列名称
            dataGridView.ColumnCount = title_str.Length + 1;
            dataGridView.ColumnHeadersVisible = true;
            DataGridViewCellStyle code = new DataGridViewCellStyle();
            code.BackColor = Color.Beige;
            code.Font = new Font("Verdana", 10, FontStyle.Bold);

            if (title_str.Length > 0)
            {
                dataGridView.Columns[0].Name = "序号";
                dataGridView.Columns[0].Width = 50;
                //dataGridView.Columns[0].ReadOnly = true;//第一列禁止编辑
                for (int i = 0; i < title_str.Length; i++)
                {
                    //dataGridView1.Columns[i + 1].ReadOnly = true;//禁止编辑
                    dataGridView.Columns[i + 1].Name = title_str[i];
                    dataGridView.Columns[i + 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    dataGridView.Columns[i + 1].FillWeight = title_width[i];
                }
            }


            //
            if (dataGridView.Columns.Count > 0)
            {
                for (int i = 0; i < dataGridView.Columns.Count; i++)
                {
                    dataGridView.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
                }
            }

        }

        /// <summary>
        /// 添加行数据
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <param name="Row_str"></param>
        /// <returns></returns>
        public int add_Column(DataGridView dataGridView, string[] Row_str)
        {
            try
            {
                //for (int i = 0; i < dataGridView1.Rows.Count; i++)
                //{
                //    if (dataGridView1.Rows[i].Cells[1].Value.ToString() == Row_str[1])
                //    {
                //        MessageBox.Show("当前名称已被使用，请检查！", "提示");
                //        return 1;
                //    }
                //    if (dataGridView1.Rows[i].Cells[2].Value.ToString() == Row_str[2])
                //    {
                //        MessageBox.Show("当前IP已被使用，请检查！", "提示");
                //        return 1;
                //    }
                //}

                DataGridViewRowCollection rows = dataGridView.Rows;
                rows.Add(Row_str);
            }
            catch { return 1; }
            return 0;
        }

        /// <summary>
        /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>
        //鼠标右键类
        ContextMenuStrip menuStrip_1 = new ContextMenuStrip();
        ToolStripMenuItem subItem_1 = new ToolStripMenuItem();

        /// <summary>
        /// 右击菜单初始化1
        /// </summary>
        private void init_RightClick()
        {
            if (menuStrip_1.Items.Count > 0) menuStrip_1.Items.Clear();
            //鼠标右击菜单
            subItem_1 = GetMenuItem("允许编辑");
            subItem_1.Click += new EventHandler(toolStripMenuItem_Click);//添加事件
            menuStrip_1.Items.Add(subItem_1);
        }

        /// <summary>
        /// 右击菜单初始化2
        /// </summary>
        private void init_RightClick2()
        {
            if (menuStrip_1.Items.Count > 0) menuStrip_1.Items.Clear();
            //鼠标右击菜单
            //subItem_1 = GetMenuItem("添加");
            //subItem_1.Click += new EventHandler(toolStripMenuItem_Click2);//添加事件
            //menuStrip_1.Items.Add(subItem_1);

            //subItem_1 = GetMenuItem("删除");
            //subItem_1.Click += new EventHandler(toolStripMenuItem_Click2);//添加事件
            //menuStrip_1.Items.Add(subItem_1);

            //subItem_1 = GetMenuItem("禁止编辑");
            //subItem_1.Click += new EventHandler(toolStripMenuItem_Click2);//添加事件
            //menuStrip_1.Items.Add(subItem_1);
        }

        /// <summary>
        /// 右击菜单添加
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="img"></param>
        /// <returns></returns>
        private ToolStripMenuItem GetMenuItem(string txt, Image img = null)
        {
            ToolStripMenuItem menuItem = new ToolStripMenuItem();
            menuItem.Text = txt;
            menuItem.Image = img;
            return menuItem;
        }

        private void toolStripMenuItem_Click(object sender, EventArgs e)
        {

            string whichcontrol_name = (sender as ToolStripMenuItem).Text;
            switch (whichcontrol_name)
            {
                case "允许编辑":
                    for (int i = 1; i < dataGridView1.Columns.Count; i++)
                    {
                        dataGridView1.Columns[i].ReadOnly = false;//允许编辑
                    }
                    init_RightClick2();
                    dataGridView1.ContextMenuStrip = menuStrip_1;

                    //鼠标选定颜色
                    dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Blue;
                    dataGridView1.DefaultCellStyle.SelectionForeColor = Color.White;
                    break;
            }
        }

        //右击菜单删除
        private void toolStripMenuItem_Click2(object sender, EventArgs e)
        {
            string whichcontrol_name = (sender as ToolStripMenuItem).Text;
            switch (whichcontrol_name)
            {
                case "禁止编辑":
                    //for (int i = 1; i < dataGridView1.Columns.Count; i++)
                    //{
                    //    dataGridView1.Columns[i].ReadOnly = true;//禁止编辑
                    //}
                    //init_RightClick();
                    //dataGridView1.ContextMenuStrip = menuStrip_1;

                    ////鼠标选定颜色
                    //dataGridView1.DefaultCellStyle.SelectionBackColor = SystemColors.Highlight;
                    //dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;
                    break;
                case "添加":
                    if (this.dataGridView1.Rows.Count >= 8)
                    {
                        MessageBox.Show("已经是多设备8个", "提示");
                        return;
                    }
                    string[] titel_str = new string[] { dataGridView1.RowCount.ToString(), "", "192.168.1.1", "102", "未连接" };
                    add_Column(dataGridView1, titel_str);
                    break;
                case "删除":
                    if (RowIndex >= 0 && !this.dataGridView1.Rows[RowIndex].IsNewRow)
                    {
                        this.dataGridView1.Rows.RemoveAt(RowIndex);//移除行
                    }
                    RowIndex = -1;
                    break;
            }
            //update_sort();
        }

        //配合右击菜单删除
        int RowIndex = -1;

        private void dataGridView1_CellMouseDown_1(object sender, DataGridViewCellMouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Right)
            //{
            //    this.dataGridView1.Rows[e.RowIndex].Selected = true;//启动点击选中
            //    RowIndex = e.RowIndex;//读取点击启动行号
            //    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[1];//设置为单行选中
            //    //this.menuStrip_1.Show(this.dataGridView1, e.Location);//设置contextMenuStrip1控件显示和dataGriView控件绑定
            //    //menuStrip_1.Show(Cursor.Position);//设置contextMenuStrip1控件的显示座标
            //}
            //else
            //{
            //    string[] str = gridview_tobox(e.RowIndex, e.ColumnIndex);
            //    if (str != null)
            //    {
            //        materialLabel1.Text = "工位名称： " + str[1];
            //        materialLabel2.Text = "设备IP： " + str[2];
            //        materialLabel3.Text = "设备端口号： " + str[3];
            //        materialLabel4.Text = "设备联机状态： " + str[4];
            //    }
            //}
        }


        //添加与删除后重新排序
        public void update_sort()
        {
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                dataGridView1.Rows[i].Cells[0].Value = i.ToString();
            }

        }

        //自动生成排序序号
        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow r = this.dataGridView1.Rows[i];
                //r.HeaderCell.Value = string.Format("{0}", i + 1);
                r.Cells[0].Value = string.Format("{0}", i + 1);
            }
            this.dataGridView1.Refresh();
        }


        string str_buf = "";
        //编辑完成事件
        private void dataGridView1_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
        {
            ;
            //判断IP是否符合要求
            //string str = dataGridView1.Rows[e.RowIndex].Cells[2].Value?.ToString();
            //if (IsServerAddress(str))
            //{
            //    dataGridView1.Rows[e.RowIndex].Cells[2].Value = str;
            //}
            //else
            //{
            //    dataGridView1.Rows[e.RowIndex].Cells[2].Value = str_buf;
            //    str_buf = "";
            //}

        }


        //编辑中事件
        private void dataGridView1_EditingControlShowing_1(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl;
            if (editingControl != null)
            {
                str_buf = editingControl.Text;
            }
        }


        //返回鼠标点击行的所有数据
        private string[] gridview_tobox(int Rows, int columns)
        {
            string[] tabel_str = new string[dataGridView1.Columns.Count];
            try
            {
                if (Rows > -1)
                {
                    for (int j = 0; j < (dataGridView1.Columns.Count); j++)
                    {
                        tabel_str[j] = Convert.ToString(dataGridView1.Rows[Rows].Cells[j].Value);

                    }
                    return tabel_str;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }

        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public int Serialize<T>(T source, string file_path)//序列化方法  
        {
            if (!typeof(T).IsSerializable)
            {
                //MessageBox.Show("类型必须是可序列化", "提示");
                return 1;
            }

            if (Object.ReferenceEquals(source, null))
            {
                //MessageBox.Show("实例不是相同的实例", "提示");
                return 2;
            }
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Create))//创建一个文件流，对文件进行写入
                {
                    BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
                    bf.Serialize(fs, source); //序列化到硬盘
                    fs.Close();//关闭文件流
                }
                return 0;
            }
            catch
            {
                return 3;
            }
        }
        public T Deserialize<T>(string file_path)
        {
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// DataTable表数据显示到DataGridview 必须要有列名并与DataTable对齐
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="dataGridView">DataGridView</param>
        /// <returns>true成功；false失败</returns>
        public int GridviewShowDataTable(DataTable table, DataGridView dataGridView)
        {
            try
            {
                if (table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        dataGridView.Rows.Add();
                        dataGridView.Rows[i].Cells[0].Value = i;
                        for (int j = 0; j < (table.Columns.Count - 1); j++)
                        {
                            dataGridView.Rows[i].Cells[j + 1].Value = table.Rows[i].ItemArray[j + 1].ToString();
                            //Application.DoEvents();//可以交出控制权但是慢
                        }
                    }
                }

                return 0;
            }
            catch (Exception ex)
            { return 1; }

        }

        /// <summary>
        /// DataGridView导出为Datatable
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <returns>Datatable</returns>
        public DataTable GetDataGridView(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }



    }
}
